package com.mylearn.myblog.controller;

import com.mylearn.myblog.entity.User;
import com.mylearn.myblog.service.UserService;
import com.mylearn.myblog.util.BaseResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/admin")
@Api(value = "管理员接口",description = "管理员接口")
public class LoginController {

	@Autowired
	private UserService userService;

	@ApiOperation(value = "管理员登录",notes = "管理员登录")
	@RequestMapping(value = "/login",method = RequestMethod.POST)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "username", value = "用户名", dataType = "String", paramType = "query", required = true),
			@ApiImplicitParam(name = "password", value = "密码", dataType = "String", paramType = "query", required = true)
	})
	public BaseResult Login(@RequestParam String username, @RequestParam String password, HttpSession session){
		User user = userService.checkUser(username, password);
		if(user!=null){
			session.setAttribute("user",user);
			return BaseResult.ok(user);
		}else {
			BaseResult.Error error = new BaseResult.Error("信息","错误");
			List<BaseResult.Error> errors = new ArrayList<>();
			errors.add(error);
			return BaseResult.notOk(errors);
		}
	}

	@ApiOperation(value = "管理员退出登录",notes = "管理员退出登录")
	@RequestMapping(value = "/logout",method = RequestMethod.GET)
	public BaseResult Logout(HttpSession session){
		session.removeAttribute("user");
		return BaseResult.ok();
	}
}
